<template>
  <div class="quotation-list">
    <!-- 添加查询条件 -->
    <view>
      <a-card :bordered="false" class="search-card card-wrapper">
        <a-form
          :model="searchParams"
          layout="inline"
          class="search-form"
        >
          <div class="search-container">
            <div class="search-item" style="width: 16%;">
              <label class="search-label">单号:</label>
              <div class="search-input">
                <a-input
                  v-model:value="searchParams.xmqducdocno"
                  placeholder="请输入单号"
                  allow-clear
                />
              </div>
            </div>

            <div class="search-item" style="width: 15%;">
              <label class="search-label">版本:</label>
              <div class="search-input">
                <a-input
                  v-model:value="searchParams.xmqduc001"
                  placeholder="请输入版本"
                  allow-clear
                />
              </div>
            </div>

            <div class="search-item" style="width: 17%;">
              <label class="search-label">客户编号:</label>
              <div class="search-input">
                <a-input
                  v-model:value="searchParams.xmqduc007"
                  placeholder="请输入客户编号"
                  allow-clear
                />
              </div>
            </div>

            <div class="search-item" style="width: 18%;">
              <label class="search-label">创建日期:</label>
              <div class="search-input">
                <a-date-picker
                  v-model:value="searchParams.xmqduccrtdt"
                  placeholder="请选择创建日期"
                  style="width: 100%"
                />
              </div>
            </div>

            <div class="search-item" style="width: 15%;">
              <label class="search-label">状态:</label>
              <div class="search-input">
                <a-select
                  v-model:value="searchParams.xmqducstus"
                  placeholder="请选择状态"
                  :options="dropdownOptions.quoteCheckOptions"
                  allow-clear
                  style="width: 100%"
                />
              </div>
            </div>
            <a-button type="primary" @click="handleSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="handleReset">
              <template #icon>
                <RedoOutlined />
              </template>
              重置
            </a-button>
          </div>
        </a-form>
        <div class="search-buttons-wrapper">
          <div class="search-buttons">
            <a-space>
              <a-button
                type="primary"
                :disabled="selectedRows.length === 0"
                @click="exportSelected"
                :loading="exportLoading"
              >
                <template #icon>
                  <DownloadOutlined />
                </template>
                批量导出
              </a-button>
              <a-button
                type="default"
                :disabled="selectedRows.length === 0"
                @click="previewSelected"
                :loading="previewLoading"
              >
                <template #icon>
                  <EyeOutlined />
                </template>
                在线预览
              </a-button>
              <a-button
                type="primary"
                :disabled="selectedRows.length === 0 || selectedRows.length > 1"
                @click="handleEdit"
              >
                <template #icon>
                  <EditOutlined />
                </template>
                编辑
              </a-button>
              <!-- <a-button
                type="primary"
                :disabled="selectedRows.length === 0 || selectedRows.length > 1"
                @click="handleEditInquiry"
              >
                报价单编辑查询
              </a-button> -->
            </a-space>
          </div>
        </div>
      </a-card>
    </view>

    <a-card title="" :bordered="false" class="mt-3" headStyle="min-height: 2.08vw;" bodyStyle="padding: 0.8vw 1.25vw;">
      <div class="table-container">
        <SortableTable
          :data="paginatedDataWithStatusText"
          :columns="columns"
          :row-colors="['white', '#EFF4F9']"
          :row-height="'1.67vw'"
          :font-size="'0.9vw'"
          :show-sort-indicators="true"
          :sorted-indicator-color="'#fff'"
          :unsorted-indicator-color="'rgba(255, 255, 255, 0.5)'"
          @sort-change="handleSortChange"
          :fixed-action="true"
          :get-row-class="getRowClass"
          @row-dblclick="handleRowDblClick"
        >
          <template #column-index="{ index }">
            {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
          </template>

          <template #column-selection="{ item }">
            <a-checkbox
              :checked="selectedRows.some(row => row.xmqducdocno === item.xmqducdocno && row.xmqduc001 === item.xmqduc001)"
              @change="(e) => handleRowSelection(e, item)"
              @click.stop
            />
          </template>

          <template #header-selection>
            <a-checkbox
              :checked="isAllSelected"
              :indeterminate="isIndeterminate"
              @change="handleSelectAll"
            />
          </template>

          <template #column-actions="{ item }">
            <div class="action-cell">
              <a-button type="link" @click="showDrawer(item)">查看</a-button>
            </div>
          </template>
        </SortableTable>

        <!-- 无数据提示 -->
        <div v-if="paginatedData.length === 0" class="no-data">
          暂无数据
        </div>
      </div>

      <div class="pagination-wrapper">
        <a-pagination
          v-model:current="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :show-size-changer="true"
          :page-size-options="pagination.pageSizeOptions"
          @change="handlePageChange"
          @show-size-change="handlePageSizeChange"
        />
      </div>
    </a-card>

    <!-- Excel在线预览组件 -->
    <ExcelPreview
      v-model:visible="previewVisible"
      :file-url="previewFileUrl"
      :file-name="previewFileName"
      @close="closePreview"
      @retry="previewSelected"
    />

    <QuotationDetailDrawer
      :visible="open"
      :quotation-data="currentQuotation"
      @close="open = false"
      @update:visible="open = $event"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue';
import { useRouter } from 'vue-router';
import dayjs from 'dayjs';
import { SortableTable } from '@/components/custom';
import {
  qecutListApi, // 模切报价单列表接口
  getDitcApi, //获取模切报价单详情的下拉列表数据
  qecutExportsApi, // 模切报价单批量导出接口
} from '@/service/api/modules/die-cutting/die-cutting';
import { useRouterPush } from '@/hooks/common/router';
import QuotationDetailDrawer from './modules/quotation-detail-drawer.vue';
import ExcelPreview from '@/components/custom/excel-preview.vue';
import { message } from 'ant-design-vue';
import {
  SearchOutlined,
  RedoOutlined,
  DownloadOutlined,
  EyeOutlined,
  EditOutlined
} from '@ant-design/icons-vue';

const router = useRouter();
const { routerPushByKey } = useRouterPush();

// 添加下拉选项数据
const dropdownOptions = reactive({
  quoteCheckOptions: []
});

// 控制行是否可点击
const enableRowClick = ref(true);

// 查询参数
const searchParams = reactive({
  xmqducdocno: null,  // 单号
  xmqduc001: null,    // 版本
  xmqduc007: null,    // 产品编码
  xmqduccrtdt: null,  // 资料创建日
  xmqducstus: null    // 状态
});

// 选中的行
const selectedRows = ref([]);

// 计算是否全选
const isAllSelected = computed(() => {
  return paginatedDataWithStatusText.value.length > 0 &&
         selectedRows.value.length === paginatedDataWithStatusText.value.length;
});

// 计算是否部分选中
const isIndeterminate = computed(() => {
  return selectedRows.value.length > 0 &&
         selectedRows.value.length < paginatedDataWithStatusText.value.length;
});

// 表格列定义
const columns = [
  {
    key: 'selection',
    label: '', // 保持为空，使用自定义表头模板
    width: '3.125vw'
  },
  {
    key: 'index',
    label: '序号',
    width: '3.125vw'
  },
  {
    key: 'xmqduc007',
    label: '客户编号',
    width: '6.25vw'
  },
  {
    key: 'xmqduc007Name',
    label: '客户名称',
    width: '15vw'
  },
  {
    key: 'xmqducdocno',
    label: '单号',
    width: '9vw'
  },
  {
    key: 'xmqduc001',
    label: '版本',
    width: '3.125vw'
  },
  {
    key: 'xmqducstusText',
    label: '状态',
    width: '4.17vw'
  },
  // {
  //   key: 'xmqducstus',
  //   label: '状态码',
  //   width: '4.17vw'
  // },
  {
    key: 'xmqduc002',
    label: '报价申请单号',
    width: '9vw'
  },
  {
    key: 'xmqduc003',
    label: '报价申请单版本',
    width: '8vw'
  },
  {
    key: 'xmqduc004',
    label: '产品编码',
    width: '8vw'
  },
  {
    key: 'xmqduc011Name',
    label: '报价人员',
    width: '5.21vw'
  },
  {
    key: 'xmqduc005',
    label: '品名',
    width: '10vw'
  },
  {
    key: 'xmqduc006',
    label: '规格',
    width: '10vw'
  },
  {
    key: 'xmqduc008',
    label: '客户货号',
    width: '8vw'
  },
  {
    key: 'xmqduc009',
    label: 'Model',
    width: '6vw'
  },
  {
    key: 'xmqduc010',
    label: '终端货号',
    width: '7vw'
  },
  // {
  //   key: 'xmqduc012',
  //   label: '报价部门',
  //   width: '5.21vw'
  // },
  // {
  //   key: 'xmqduc013',
  //   label: '报价币种',
  //   width: '5vw'
  // },
  // {
  //   key: 'xmqduc014',
  //   label: '税种',
  //   width: '4.17vw'
  // },
  // {
  //   key: 'xmqduc015',
  //   label: '报价数量',
  //   width: '5vw'
  // },
  {
    key: 'xmqduccrtdt',
    label: '资料创建日',
    width: '9vw'
  },
  {
    key: 'xmqducmoddt',
    label: '最近修改日',
    width: '9vw'
  },
  // {
  //   key: 'actions',
  //   label: '操作',
  //   width: '6.25vw',
  //   fixed: true
  // }
];

// 表格数据（写死的数据）
const tableData = ref([]);
// 状态码映射
const statusMap = ref({});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 100,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100']
});

const getDitc = () => {
  getDitcApi().then(res => {
    const data = res.data;
      // 处理quote_check数据，用于状态查询下拉选项
      if (data.quote_check && Array.isArray(data.quote_check)) {
        dropdownOptions.quoteCheckOptions = data.quote_check.map(item => ({
          label: item.gzcbl004,
          value: item.gzcbl002
        }));
        console.log('quote_check:', dropdownOptions);
        // 构建状态码映射
        const statusMapping = {};
        data.quote_check.forEach(item => {
          statusMapping[item.gzcbl002] = item.gzcbl004;
        });
        statusMap.value = statusMapping;
        console.log('statusMap:', statusMap);
        // 更新搜索表单中的选项
        // initDropdownOptions();
      }
  });
};

// 初始化下拉选项
// const initDropdownOptions = () => {
//   // 查找状态字段的索引
//   const statusFieldIndex = searchFormList.value.findIndex(item => item.key === 'xmqducstus');

//   // 如果找到了状态字段，则更新其选项
//   if (statusFieldIndex !== -1) {
//     // 直接修改响应式数组中的特定元素
//     searchFormList.value[statusFieldIndex] = {
//       ...searchFormList.value[statusFieldIndex],
//       selectOptions: [...dropdownOptions.quoteCheckOptions]
//     };

//     // 触发响应式更新
//     searchFormList.value = [...searchFormList.value];
//     console.log('searchFormList:', searchFormList);
//   }
// };

const qecut = () => {
  // 使用动态分页参数
  const params = {
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
    templateCode: 'T001', // 添加固定的templateCode参数
    ...searchParams
  };

  // 修复日期参数格式问题
  if (params.xmqduccrtdt && typeof params.xmqduccrtdt === 'object' && params.xmqduccrtdt.$d) {
    // 如果是 dayjs 对象，转换为标准日期字符串格式
    params.xmqduccrtdt = dayjs(params.xmqduccrtdt.$d).format('YYYY-MM-DD');
  } else if (params.xmqduccrtdt === null || params.xmqduccrtdt === undefined || params.xmqduccrtdt === '') {
    // 如果日期为空，确保传递 null 值
    params.xmqduccrtdt = null;
  }

  console.log('查询参数:', params)

  qecutListApi(params).then(res => {
    const data = res.otherData;
    console.log('接口参数:', params);
    if (data.code === 200) {
      tableData.value = data.rows;
      // 使用响应式赋值更新 total（已 reactive，直接赋值即为"setter"行为）
      pagination.total = data.total;
    }
    console.log('接口返回数据:', data);
  });
}

// 修复：直接使用后端返回的数据，不再进行前端分页
const paginatedData = computed(() => {
  return tableData.value;
});

// 自定义行类名函数，用于添加行点击样式
const getRowClass = (index) => {
  const baseClass = index % 2 === 0 ? 'table-row-even' : 'table-row-odd';
  // 如果启用行点击功能，添加可点击样式
  return enableRowClick.value ? `${baseClass} clickable-row` : baseClass;
};

// 处理排序变化
const handleSortChange = (sortState) => {
  console.log('排序状态:', sortState);
  // 在这里可以处理排序逻辑
};

// 处理分页变化
const handlePageChange = (page, pageSize) => {
  pagination.current = page;
  pagination.pageSize = pageSize;
  // 分页变化时重新查询数据
  qecut();
};

// 处理页面大小变化
const handlePageSizeChange = (current, size) => {
  pagination.current = current;
  pagination.pageSize = size;
  // 页面大小变化时重新查询数据
  qecut();
};

// 跳转到详情页面 - 使用带参数的路由跳转
const goToDetail = (record) => {
  console.log('跳转到详情页面:', record);
  // 使用 routerPushByKey 方法跳转到报价明细页面，传递参数
  routerPushByKey('die-cutting-quotation_quotation', {
    query: {
      xmqeucdocno: record.xmqducdocno,
      xmqeuc001: record.xmqduc001,
      xmqeucent: record.xmqducent,
      tabTitle: record.xmqduc007, // 添加自定义标签页标题
      templateCode: 'T001', // 添加固定的templateCode参数
    },
  });
};

// 带状态文本的分页数据
const paginatedDataWithStatusText = computed(() => {
  return tableData.value.map((item, index) => {
    return {
      ...item,
      index: index // 为每行数据添加索引
    };
  }).map(item => {
    return {
      ...item,
      xmqducstusText: statusMap.value[item.xmqducstus] || item.xmqducstus
    };
  });
});

// 处理行双击事件
const handleRowDblClick = (item, index) => {
  console.log('双击行数据:', item);
  // 可以在这里添加行双击后的处理逻辑，例如跳转到详情页
  goToDetail(item);
};

// 查询方法
const handleSearch = () => {
  pagination.current = 1;
  qecut();
};

// 重置方法
const handleReset = () => {
  nextTick(() => {
    searchParams.xmqducdocno = null;
    searchParams.xmqduc001 = null;
    searchParams.xmqduc007 = null;
    searchParams.xmqduccrtdt = null;
    searchParams.xmqducstus = null;
    handleSearch();
  });
};

// 处理行选择
const handleRowSelection = (e, record) => {
  const checked = e.target.checked;
  if (checked) {
    // 添加到选中项
    selectedRows.value.push(record);
  } else {
    // 从选中项中移除
    const index = selectedRows.value.findIndex(
      item => item.xmqducdocno === record.xmqducdocno && item.xmqduc001 === record.xmqduc001
    );
    if (index > -1) {
      selectedRows.value.splice(index, 1);
    }
  }
};

// 全选/取消全选
const handleSelectAll = (e) => {
  const checked = e.target.checked;

  if (checked) {
    // 全选
    selectedRows.value = [...paginatedDataWithStatusText.value];
  } else {
    // 取消全选
    selectedRows.value = [];
  }
};

const open = ref<boolean>(false);
const currentQuotation = ref({}); // 用于存储当前查看的报价单数据

// 预览相关状态
const previewLoading = ref(false);
const previewVisible = ref(false);
const previewFileUrl = ref('');
const previewFileName = ref('');

const afterOpenChange = (bool: boolean) => {
  console.log('open', bool);
};

const showDrawer = (record) => {
  console.log('显示抽屉，记录数据:', record);
  // 确保传递必要的参数
  currentQuotation.value = {
    xmqducent: record.xmqducent,
    xmqducdocno: record.xmqducdocno,
    xmqduc001: record.xmqduc001
  };
  open.value = true;
};

// 在线预览选中项
const previewSelected = () => {
  if (selectedRows.value.length === 0) {
    message.error('请选择要预览的报价单');
    return;
  }

  // 构造导出数据格式
  const exportData = {
    templateCode: 'T001',
    quoteCut: selectedRows.value.map(item => ({
      xmqducent: item.xmqducent,
      xmqducdocno: item.xmqducdocno,
      xmqduc001: item.xmqduc001
    }))
  };

  previewLoading.value = true;

  qecutExportsApi(exportData)
    .then((res: any) => {
      // 检查接口返回的类型是否为Excel文件
      if (res.data.type == 'application/json') {
        // 如果是JSON格式，说明导出失败
        const errorMsg = res.otherData?.message || '获取预览文件失败';
        message.error(errorMsg);
        console.error('预览失败:', errorMsg);
        return;
      }

      // 创建Blob对象
      const blob = new Blob([res.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      });

      // 创建临时URL
      const fileURL = URL.createObjectURL(blob);
      const fileName = `报价明细_${new Date().getTime()}.xlsx`;

      // 设置预览参数
      previewFileUrl.value = fileURL;
      previewFileName.value = fileName;
      previewVisible.value = true;
    })
    .catch((error: any) => {
      const errorMsg = '预览失败: ' + (error.message || '获取预览文件失败');
      message.error(errorMsg);
      console.error('预览失败:', error);
    })
    .finally(() => {
      previewLoading.value = false;
    });
};

// 关闭预览
const closePreview = () => {
  previewVisible.value = false;
  // 清理URL对象以释放内存
  if (previewFileUrl.value) {
    URL.revokeObjectURL(previewFileUrl.value);
    previewFileUrl.value = '';
  }
};

const exportLoading = ref(false);
// 导出选中项
const exportSelected = () => {
  if (selectedRows.value.length === 0) {
    console.log('没有选中任何行');
    return;
  }

  // 构造导出数据格式
  const exportData = {
    templateCode: 'T001',
    quoteCut: selectedRows.value.map(item => ({
      xmqducent: item.xmqducent,
      xmqducdocno: item.xmqducdocno,
      xmqduc001: item.xmqduc001
    }))
  };
  exportLoading.value = true;
  console.log('导出数据:', exportData);
  qecutExportsApi(exportData).then((res: any) => {
    // 创建下载链接
    const blob = new Blob([res.data]);
    const fileName = `报价明细.xlsx`;
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    URL.revokeObjectURL(link.href);
  })
  .catch((error: any) => {
    console.error('导出失败:', error);
  })
  .finally(() => {
    exportLoading.value = false;
  });
};

// 添加编辑和编辑查询处理函数
const handleEdit = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请选择一条数据进行编辑');
    return;
  }

  if (selectedRows.value.length > 1) {
    message.warning('只能选择一条数据进行编辑');
    return;
  }

  const record = selectedRows.value[0];
  // 跳转到报价单编辑页面
  routerPushByKey('die-cutting-quotation_maintenance-management_quotation-edit', {
    query: {
      xmqeucdocno: record.xmqducdocno,
      xmqeuc001: record.xmqduc001,
      xmqeucent: record.xmqducent,
      tabTitle: record.xmqduc007, // 添加自定义标签页标题
      templateCode: 'T001', // 添加固定的templateCode参数
    },
  });
};

// const handleEditInquiry = () => {
//   if (selectedRows.value.length === 0) {
//     message.warning('请选择一条数据进行编辑查询');
//     return;
//   }

//   if (selectedRows.value.length > 1) {
//     message.warning('只能选择一条数据进行编辑查询');
//     return;
//   }

//   const record = selectedRows.value[0];
//   // 跳转到报价单编辑查询页面
//   routerPushByKey('die-cutting-quotation_quotation-edit-inquiry', {
//     query: {
//       xmqeucdocno: record.xmqducdocno,
//       xmqeuc001: record.xmqduc001,
//       xmqeucent: record.xmqducent,
//       tabTitle: record.xmqduc007 // 添加自定义标签页标题
//     },
//   });
// };

// 移除原来的行点击事件处理函数
// 启用行点击功能的方法（可以在需要的地方调用此方法设置enableRowClick.value = true）
// 例如：onMounted(() => { enableRowClick.value = true; });

// onMounted(() => {
//   qecut();
//   getDitc();
// });

// 添加onActivated钩子，确保每次进入页面都重新请求接口数据
import { onActivated } from 'vue';
onActivated(() => {
  // 使用nextTick确保在DOM更新后再执行查询
  nextTick(() => {
    qecut();
    getDitc();
  });
});
</script>

<style scoped>
.quotation-list {
  /* background-color: #fff; */
  padding: 0.52vw 0.83vw;
  border-radius: 0.21vw;
  height: calc(100vh - 6.25vw); /* 自适应高度，减去顶部和其他元素的高度 */
  display: flex;
  flex-direction: column;
}

:deep(.ant-card) {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.ant-card-body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-container {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.pagination-wrapper {
  margin-top: 0.52vw;
  display: flex;
  justify-content: flex-end;
}

.action-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.no-data {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #999;
  font-size: 0.73vw;
}

/* 可点击行的样式 */
.clickable-row {
  cursor: pointer;
}

.clickable-row:hover {
  background-color: #e6f7ff !important;
}

.search-container {
  display: flex;
  flex-wrap: wrap;
  gap: 1vw;
  align-items: flex-start;
  width: 100%;
}

.search-item {
  display: flex;
  align-items: center;
  /* flex-direction: column; */
  /* flex-shrink: 0; */
}

.search-label {
  font-size: 0.9vw;
  /* margin-bottom: 4px; */
  margin-right: 5px;
  color: #000000;
  white-space: nowrap;
}

.search-input {
  flex: 1;
  min-width: 0;
}

:deep(.ant-input) {
  font-size: 0.9vw;
}

:deep(.ant-select) {
  font-size: 0.9vw;
}

:deep(.ant-picker) {
  font-size: 0.9vw;
}

:deep(.ant-btn) {
  font-size: 0.9vw;
  height: 2vw;
  padding: 0.1vw 0.6vw;
  border-radius: 0.2vw;
}

.search-buttons-wrapper {
  flex: 1 0 100%;
  min-width: 200px;
  margin-top: 0.5vw;
}

.search-buttons {
  display: flex;
  justify-content: flex-start;
  width: 100%;
  padding-bottom: 4px;
}

/* 响应式处理 */
@media (max-width: 1200px) {
  .search-container {
    flex-wrap: wrap;
  }

  .search-item {
    width: calc(33.33% - 16px) !important;
  }

  .search-buttons-wrapper {
    margin-left: 0;
    width: 100% !important;
  }
}

@media (max-width: 768px) {
  .search-item {
    width: calc(50% - 16px) !important;
  }
}

@media (max-width: 576px) {
  .search-item {
    width: 100% !important;
  }
}

/* 按钮图标上下对齐 */
:deep(.ant-btn) {
  font-size: 0.9vw;
  height: 2vw;
  padding: 0.1vw 0.6vw;
  border-radius: 0.2vw;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  box-shadow: none;
}
</style>
